<script setup>
import { ref, computed, watch } from 'vue'

// Props
const props = defineProps({
  modelValue: {
    type: Object,
    default: () => ({
      province: '',
      city: '',
      district: '',
    }),
  },
  show: {
    type: Boolean,
    default: false,
  },
  provinceData: {
    type: Array,
    default: [],
  },
})

// Emits
const emit = defineEmits(['update:modelValue', 'update:show', 'confirm', 'cancel'])

// 当前选择的省市县
const selectedProvince = ref('')
const selectedCity = ref('')
const selectedDistrict = ref('')

// 当前显示的层级 0:省 1:市 2:县
const currentLevel = ref(0)

// 面包屑导航
const breadcrumb = computed(() => {
  const items = []
  if (selectedProvince.value) {
    items.push({ label: selectedProvince.value, level: 0 })
  }
  if (selectedCity.value) {
    items.push({ label: selectedCity.value, level: 1 })
  }
  if (selectedDistrict.value) {
    items.push({ label: selectedDistrict.value, level: 2 })
  }
  return items
})

// 当前显示的列表数据
const currentList = computed(() => {
  if (currentLevel.value === 0) {
    // 显示省份列表
    return props.provinceData.map((item) => ({ name: item.name, type: 'province' }))
  } else if (currentLevel.value === 1) {
    // 显示城市列表
    const province = props.provinceData.find((p) => p.name === selectedProvince.value)
    return province ? province.cities.map((item) => ({ name: item.name, type: 'city' })) : []
  } else if (currentLevel.value === 2) {
    // 显示区县列表
    const province = props.provinceData.find((p) => p.name === selectedProvince.value)
    const city = province?.cities.find((c) => c.name === selectedCity.value)
    return city ? city.districts.map((item) => ({ name: item, type: 'district' })) : []
  }
  return []
})

// 选择项目
const selectItem = (item) => {
  if (item.type === 'province') {
    selectedProvince.value = item.name
    selectedCity.value = ''
    selectedDistrict.value = ''
    currentLevel.value = 1
  } else if (item.type === 'city') {
    selectedCity.value = item.name
    selectedDistrict.value = ''
    currentLevel.value = 2
  } else if (item.type === 'district') {
    selectedDistrict.value = item.name
    // 选择完区县后自动确认
    confirmSelection()
  }
}

// 点击面包屑导航
const clickBreadcrumb = (level) => {
  if (level === 0) {
    selectedCity.value = ''
    selectedDistrict.value = ''
    currentLevel.value = 1
  } else if (level === 1) {
    selectedDistrict.value = ''
    currentLevel.value = 2
  }
}

// 确认选择
const confirmSelection = () => {
  const result = {
    province: selectedProvince.value,
    city: selectedCity.value,
    district: selectedDistrict.value,
    fullAddress: `${selectedProvince.value} ${selectedCity.value} ${selectedDistrict.value}`,
  }
  emit('update:modelValue', result)
  emit('confirm', result)
  closeModal()
}

// 取消选择
const cancelSelection = () => {
  emit('cancel')
  closeModal()
}

// 关闭弹窗
const closeModal = () => {
  emit('update:show', false)
  // 重置状态
  setTimeout(() => {
    currentLevel.value = 0
    selectedProvince.value = ''
    selectedCity.value = ''
    selectedDistrict.value = ''
  }, 300)
}

// 监听props变化
watch(
  () => props.modelValue,
  (newVal) => {
    if (newVal) {
      selectedProvince.value = newVal.province || ''
      selectedCity.value = newVal.city || ''
      selectedDistrict.value = newVal.district || ''
    }
  },
  { immediate: true }
)

// 返回上一级
const goBack = () => {
  if (currentLevel.value > 0) {
    currentLevel.value--
    if (currentLevel.value === 0) {
      selectedCity.value = ''
      selectedDistrict.value = ''
    } else if (currentLevel.value === 1) {
      selectedDistrict.value = ''
    }
  }
}
</script>

<template>
  <view v-if="show" class="province-picker-overlay" @click="closeModal">
    <view class="province-picker-content" @click.stop>
      <!-- 头部 -->
      <view class="picker-header">
        <view class="header-left">
          <view v-if="currentLevel > 0" class="back-btn" @click="goBack">
            <text class="back-icon">‹</text>
          </view>
          <text class="picker-title">
            {{ currentLevel === 0 ? '选择省份' : currentLevel === 1 ? '选择城市' : '选择区县' }}
          </text>
        </view>
        <view class="picker-close" @click="closeModal">
          <text>×</text>
        </view>
      </view>

      <!-- 面包屑导航 -->
      <view v-if="breadcrumb.length > 0" class="breadcrumb">
        <view
          v-for="(item, index) in breadcrumb"
          :key="index"
          class="breadcrumb-item"
          @click="clickBreadcrumb(item.level)"
        >
          <text>{{ item.label }}</text>
          <text v-if="index < breadcrumb.length - 1" class="breadcrumb-separator">></text>
        </view>
      </view>

      <!-- 列表内容 -->
      <scroll-view class="picker-list" scroll-y>
        <view
          v-for="(item, index) in currentList"
          :key="index"
          class="picker-item"
          @click="selectItem(item)"
        >
          <text class="item-name">{{ item.name }}</text>
          <text class="item-arrow">></text>
        </view>

        <view v-if="currentList.length === 0" class="empty-tip">
          <text>暂无数据</text>
        </view>
      </scroll-view>

      <!-- 底部按钮 -->
      <view v-if="selectedDistrict" class="picker-footer">
        <view class="footer-btn cancel-btn" @click="cancelSelection">
          <text>取消</text>
        </view>
        <view class="footer-btn confirm-btn" @click="confirmSelection">
          <text>确认</text>
        </view>
      </view>
    </view>
  </view>
</template>

<style src="./style.scss" scoped />
